<?php
/**
 * @title 32. 最长有效括号 - 少用额外空间
 * @author start2004
 */

class Solution {

    /**
     * @param String $s
     * @return Integer
     */
    function longestValidParentheses($s) {
        /**
         * @since 2020-07-21 长度
         */
        $len = strlen($s);

        /**
         * @since 2020-07-21 最大有效长度
         */
        $maxLength = 0;

        /**
         * @since 2020-07-21 正向查找
         */
        $left = $right = 0;
        for ($i=0; $i<$len; $i++){
            if($s[$i] == "("){
                $left++;
            } else {
                $right++;
            }

            if($left == $right){
                $maxLength = max($maxLength, $right<<1);
            } elseif ($left < $right) {
                $left = $right = 0;
            } else {}
        }

        /**
         * @since 2020-07-21 反向查找
         */
        $left = $right = 0;
        for ($i=$len-1; $i>=0; $i--){
            if($s[$i] == "("){
                $left++;
            } else {
                $right++;
            }

            if($left == $right){
                $maxLength = max($maxLength, $right<<1);
            } elseif ($left > $right) {
                $left = $right = 0;
            } else {}
        }

        /**
         * @return
         */
        return $maxLength;
    }
}


/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.04_2.php
 */
$datas = [
    // "",
    "(()))())(",
    // ")()())",
    // "(()(()",
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->longestValidParentheses($data);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
